import { useState, useEffect } from 'react';
import { Table, message, Select, Space, Button, Form, Input, Tag } from 'antd';
const { Option } = Select;
import { courseService, experimentCourseService, theClassService, teacherService } from '@/service';
import { executeActionAfterReq } from '@/util/errorHandle';
import styles from './index.less';

function ExperimentCoursePage() {
  const [canChange, setCanChange] = useState(true);
  const [showDialog, setShowDialog] = useState(false);
  const [action, setAction] = useState('NONE');
  const [courseData, setCourseData] = useState([]);
  const [experimentCourseData, setExperimentCourseData] = useState([]);
  const [theClassData, setTheClassData] = useState([]);
  const [teacherData, setTeacherData] = useState([]);
  useEffect(() => {
    getAllCourse();
    getAllExperimentCourse();
    getAllTheClass();
    getAllTeacher();
  }, []);

  const getAllCourse = async () => {
    const res = await courseService.getAllCourse().catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, () => {
      setCourseData(res?.data);
    })
  }
  const getAllExperimentCourse = async () => {
    const res = await experimentCourseService.getAllExperimentCourse().catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, () => {
      setExperimentCourseData(res?.data);
    })
  }
  const getAllTheClass = async () => {
    const res = await theClassService.getAllTheClass().catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, () => {
      setTheClassData(res?.data);
    })
  }
  const getAllTeacher = async () => {
    const res = await teacherService.getAllTeacher().catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, () => {
      setTeacherData(res?.data);
    })
  }

  const columns = [
    {
      title: '实验编号',
      dataIndex: 'ecId',
      key: 'ecId',
      sorter: (a: any, b: any) => a.ecId - b.ecId,
      sortDirections: ['ascend'],
    },
    {
      title: '实验课程',
      dataIndex: 'ecTitle',
      key: 'ecTitle',
      sorter: (a: any, b: any) => a.ecTitle - b.ecTitle,
      sortDirections: ['ascend'],
    },
    {
      title: '实验类型',
      dataIndex: 'ecType',
      key: 'ecType',
    },
    {
      title: '难度',
      dataIndex: 'ecDifficultyDegree',
      key: 'ecDifficultyDegree',
    },
    {
      title: '课时',
      dataIndex: 'ecHours',
      key: 'ecHours',
    },
    {
      title: '安排周次',
      dataIndex: 'arrangeWeekly',
      key: 'arrangeWeekly',
    },
    {
      title: '实验员',
      dataIndex: 'tIds',
      key: 'tIds',
      filters: teacherData.map((item: any) => ({
        text: item?.tId,
        value: item?.tId,
      })),
      onFilter: (value: any, record: any) => 
        record?.tIds?.split(',')?.map((item: any) => Number(item))?.includes(value),
      render: (text: any) => <>{
        text?.split(',')
          ?.filter((item: any) => item)
          ?.map((item: any) => (
            <Tag color="blue" key={item}>
              {item}
            </Tag>
          ))
      }</>,
      width: '100px',
    },
    {
      title: '课程编号',
      dataIndex: 'cId',
      key: 'cId',
      filters: courseData.map((item: any) => ({
        text: item?.cId,
        value: item?.cId,
      })),
      onFilter: (value: any, record: any) => value == record?.cId,
      render: (text: any) => (<Tag 
      color="blue" key={text}>
        {text}
      </Tag>),
    },
    {
      title: '开课班级',
      dataIndex: 'taughtClass',
      key: 'taughtClass',
      filters: theClassData.map((item: any) => ({
        text: item?.tcId,
        value: item?.tcId,
      })),
      onFilter: (value: any, record: any) => 
        record?.taughtClass?.split(',')?.map((item: any) => Number(item))?.includes(value),
      render: (text: any) => <>{
        text?.split(',')
          ?.filter((item: any) => item)
          ?.map((item: any) => (
            <Tag color="blue" key={item}>
              {item}
            </Tag>
          ))
      }</>,
      width: '100px',
    },
    {
      title: '课程人数',
      dataIndex: 'totalNumber',
      key: 'totalNumber',
      width: '90px',
    },
    {
      title: '操作',
      key: 'action',
      render: (text: any, record: any) => (
        <Space size="middle">
          <Button type="link" size ="small" className={styles.link} onClick={() => handleEdit(record)}>修改</Button>
          <Button type="link" size ="small" className={styles.link} onClick={() => handleDel(record)} danger>删除</Button>
        </Space>
      ),
    },
  ];

  const [form] = Form.useForm();
  form.setFieldsValue({});
  
  const handleEdit = (record: any) => {
    setCanChange(false);
    form.resetFields();
    form.setFieldsValue({
      ...record,
      taughtClass: record?.taughtClass?.split(',')?.filter((item: any) => item)?.map((item: any) => Number(item)),
      tIds: record?.tIds?.split(',')?.filter((item: any) => item)?.map((item: any) => Number(item)),
    });
    setShowDialog(true);
    setAction('EDIT');
  }
  const handleDel = async (record: any) => {
    const res = await experimentCourseService.destroyExperimentCourse(record).catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, async () => {
      message.info('删除成功');
      await getAllExperimentCourse();
    })
  }
  const handleAdd = () => {
    setCanChange(true);
    form.resetFields();
    setShowDialog(true);
    setAction('ADD');
  }
  const handleCancel = () => {
    setShowDialog(false);
  }
  const handleSubmit = async (values: any) => {
    // 提交时将数组类型转换为字符串类型
    values.taughtClass = values?.taughtClass?.join(',');
    values.tIds = values?.tIds?.join(',');
    if (action === 'EDIT') {
      const res = await experimentCourseService.updateExperimentCourse(values).catch(() => {
        message.error('请求错误');
      });
      executeActionAfterReq(res, async () => {
        message.info('修改成功');
        await getAllExperimentCourse();
        setShowDialog(false);
      })
    } else if (action === 'ADD') {
      const res = await experimentCourseService.appendExperimentCourse(values).catch(() => {
        message.error('请求错误');
      });
      executeActionAfterReq(res, async () => {
        message.info('添加成功');
        await getAllExperimentCourse();
        setShowDialog(false);
      })
    } else {
      message.error('指定动作错误');
    }
    
    // 修改课程的授课实验员
    const res = await experimentCourseService.getAllExperimentCourse().catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, async () => {
      const experimentCourse = res?.data?.filter((item: any) => values?.cId == item?.cId);
      let tIds = new Set();
      experimentCourse?.forEach((item: any) => {
        tIds = new Set([...tIds, ...(item?.tIds?.split(',') || [])]);
      })
      courseService.updateCourse({
        cId: values?.cId,
        tIds: tIds?.join(','),
        ecIds: experimentCourse?.map((item: any) => item.ecId).join(','),
      });
    })
  }
  const onTeacherChange = (value: Array<Number>) => {
    form.setFieldsValue({
      tIds: value,
    });
  }
  const onEcTypeChange = (value: string) => {
    form.setFieldsValue({
      ecType: value,
    });
  }
  const onCIdChange = (value: string | Number) => {
    form.setFieldsValue({
      cId: value,
      taughtClass: (courseData?.find((item: any) => value === item.cId))
        ?.taughtClass?.split(',').map((item: any) => Number(item)),
      totalNumber: (courseData?.find((item: any) => value === item.cId))?.totalNumber,
    });
  }
  
  return (
    <div className={styles.experimentCourse}>
      <Button type="primary" className={styles.add} onClick={handleAdd}>添加实验课程</Button>
      <Table dataSource={experimentCourseData} columns={columns} style={{minHeight: "700px"}} />
      <div className={styles.formdiv} style={{display: showDialog ? 'block' : 'none'}}>
        <Form
          name="basic"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          form={form}
          autoComplete="off"
          onFinish={handleSubmit}
          className={styles.form}
        >
          <Form.Item label="实验编号" name="ecId" rules={[{ required: true }]}>
            <Input disabled={!canChange} />
          </Form.Item>
          <Form.Item label="实验课程" name="ecTitle" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item label="实验类型" name="ecType" rules={[{ required: true }]}>
            <Select
              placeholder="请选择"
              onChange={onEcTypeChange}
            >
              <Option value='验证性'>验证性</Option>
              <Option value='演示性'>演示性</Option>
            </Select>
          </Form.Item>
          <Form.Item label="难度" name="ecDifficultyDegree" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item label="课时" name="ecHours" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item label="安排周次" name="arrangeWeekly">
            <Input />
          </Form.Item>
          <Form.Item label="实验员" name="tIds">
            <Select
              mode="multiple"
              allowClear
              placeholder="请选择"
              onChange={onTeacherChange}
              disabled
              defaultValue="请前往实验安排界面进行操作！"
            >
              {
                teacherData.map((item: any) => (
                  <Option value={item?.tId}>{`${item?.tId}: ${item?.tName}`}</Option>
                ))
              }
            </Select>
          </Form.Item>
          <Form.Item label="课程编号" name="cId" rules={[{ required: true }]}>
            <Select
              allowClear
              placeholder="请选择"
              onChange={onCIdChange}
            >
              {
                courseData?.map(((item: any) => (
                  <Option value={item?.cId}>{`${item?.cId}: ${item?.cTitle}`}</Option>
                )))
              }
            </Select>
          </Form.Item>
          <Form.Item label="开课班级" name="taughtClass">
            <Select
              mode="multiple"
              placeholder="请选择"
              disabled
            >
              {
                theClassData.map((item: any) => (
                  <Option value={item?.tcId}>{`${item?.tcId}: ${item?.tcName}`}</Option>
                ))
              }
            </Select>
          </Form.Item>
          <Form.Item label="课程人数" name="totalNumber">
            <Input disabled />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 5, span: 16 }}>
            <Button type="primary" htmlType="submit">
              确认
            </Button>
            <Button type="link" htmlType="button" onClick={handleCancel}>
              取消
            </Button>
          </Form.Item>
        </Form>
        <div className={styles.cover} onClick={handleCancel}></div>
      </div>
    </div>
  );
}

export default ExperimentCoursePage;
